package org.example.projecttwo.controller.user;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.example.projecttwo.common.Result;
import org.example.projecttwo.entity.dto.common.BatchDeleteUserDTO;
import org.example.projecttwo.entity.dto.common.BatchUpdateUserStatusDTO;
import org.example.projecttwo.entity.dto.common.DeleteUserDTO;
import org.example.projecttwo.entity.dto.statistics.AdjustUserPointsDTO;
import org.example.projecttwo.entity.dto.user.request.*;
import org.example.projecttwo.entity.dto.user.response.UserExportDTO;
import org.example.projecttwo.entity.enums.PointActionEnum;
import org.example.projecttwo.entity.user.User;
import org.example.projecttwo.service.Iuser.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户基础信息管理")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("/list")
    @Operation(summary = "获取用户列表", description = "分页获取用户列表，支持多种筛选条件 -- 用户管理")
    public Result<IPage<User>> listUser(
            @Parameter(description = "昵称查询") @RequestParam(required = false) String keyword,
            @Parameter(description = "账号状态筛选：0-正常,1-禁用,2-冻结") @RequestParam(required = false) Integer status,
            @Parameter(description = "认证类型筛选：0-个人 1-学生组织 2-学院部门 3-学校官方") @RequestParam(required = false) Integer authType,
            @Parameter(description = "角色筛选：0-管理员 1-普通用户") @RequestParam(required = false) Integer role,
            @Parameter(description = "学院ID筛选") @RequestParam(required = false) String collegeId,
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") long current,
            @Parameter(description = "每页数量", example = "10") @RequestParam(defaultValue = "10") long size) {
        Page<User> page = new Page<>(current, size);
        IPage<User> result = userService.pageBy(page, keyword, status, authType, role, collegeId);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取用户详情", description = "根据用户ID获取单个用户详细信息 -- 用户管理")
    public Result<User> getUser(@Parameter(description = "用户ID") @PathVariable Long id) {
        User user = userService.getById(id);
        return Result.success(user);
    }

    @PutMapping("/{id}/status")
    @Operation(summary = "更新用户状态", description = "管理员更新用户账号状态（启用/禁用/冻结） -- 用户管理")
    public Result<String> updateUserStatus(@Parameter(description = "用户ID") @PathVariable Long id, @Parameter(description = "账号状态：0-启用,1-禁用,2-冻结") @RequestParam Integer status) {
        userService.updateUserStatus(id, status);
        return Result.success("更新成功");
    }

    @PutMapping("/{id}/reset-password")
    @Operation(summary = "重置用户密码", description = "管理员重置用户密码为默认密码 -- 用户管理")
    public Result<String> resetUserPassword(@Parameter(description = "用户ID") @PathVariable Long id) {
        userService.resetUserPassword(id);
        return Result.success("重置成功");
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户", description = "管理员删除指定用户 -- 用户管理")
    public Result<String> deleteUser(@Parameter(description = "用户ID") @PathVariable Long id, @Valid @RequestBody DeleteUserDTO deleteDto) {
        userService.deleteUser(id, deleteDto);
        return Result.success("删除成功");
    }

    @GetMapping("/export/current")
    @Operation(summary = "导出当前用户信息", description = "导出当前登录用户的信息 -- 个人信息")
    public Result<UserExportDTO> exportCurrentUser() {
        UserExportDTO userExportDTO = userService.exportCurrentUser();
        return Result.success(userExportDTO);
    }

    @PutMapping("/batch/status")
    @Operation(summary = "批量更新用户状态", description = "管理员批量更新多个用户的状态 -- 用户管理")
    public Result<String> batchUpdateUserStatus(@Valid @RequestBody BatchUpdateUserStatusDTO dto) {
        userService.batchUpdateUserStatus(dto);
        return Result.success("批量更新状态成功");
    }

    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量删除用户", description = "管理员批量删除多个用户 -- 用户管理")
    public Result<String> batchDeleteUser(@Valid @RequestBody BatchDeleteUserDTO dto) {
        userService.batchDeleteUser(dto);
        return Result.success("批量删除成功");
    }

    @PostMapping("/batch/export")
    @Operation(summary = "批量导出用户", description = "批量导出用户数据 -- 用户管理")
    public Result<List<UserExportDTO>> batchExportUser(@RequestBody List<Long> ids) {
        List<UserExportDTO> users = userService.batchExportUser(ids);
        return Result.success(users);
    }

    @PostMapping
    @Operation(summary = "创建用户", description = "管理员创建新用户 -- 用户管理")
    public Result<User> createUser(@Valid @RequestBody CreateUserDTO createUserDTO) {
        if (!createUserDTO.getPassword().equals(createUserDTO.getConfirmPassword())) {
            return Result.error("两次输入的密码不一致");
        }

        User user = convertToUser(createUserDTO);
        User createdUser = userService.createUser(user);
        return Result.success(createdUser);
    }

    @PutMapping
    @Operation(summary = "更新用户信息", description = "管理员更新用户信息 -- 用户管理")
    public Result<User> updateUser(@Valid @RequestBody UpdateUserDTO updateUserDTO) {
        User user = convertToUser(updateUserDTO);
        User updatedUser = userService.updateUser(user);
        return Result.success(updatedUser);
    }

    @PutMapping("/{id}/switch-status")
    @Operation(summary = "切换用户状态", description = "管理员切换用户账号状态 -- 用户管理")
    public Result<String> switchUserStatus(@Parameter(description = "用户ID") @PathVariable Long id, @Valid @RequestBody SwitchUserStatusDTO dto) {
        userService.switchUserStatus(id, dto.getStatus());
        return Result.success("状态切换成功");
    }

    @PutMapping("/{id}/switch-role")
    @Operation(summary = "切换用户角色", description = "管理员切换用户角色 -- 用户管理")
    public Result<String> switchUserRole(@Parameter(description = "用户ID") @PathVariable Long id, @Valid @RequestBody SwitchUserRoleDTO dto) {
        userService.switchUserRole(id, dto.getRoleCode());
        return Result.success("角色切换成功");
    }

    @PutMapping("/{id}/adjust-points")
    @Operation(summary = "手动调整用户积分", description = "管理员手动调整用户积分 -- 用户管理")
    public Result<String> adjustUserPoints(@Parameter(description = "用户ID") @PathVariable Long id, @Valid @RequestBody AdjustUserPointsDTO dto) {
        userService.adjustUserPoints(id, dto.getType(), dto.getValue());
        return Result.success("积分调整成功");
    }

    @PutMapping("/{id}/adjust-points-by-action/{actionCode}")
    @Operation(summary = "根据积分行为调整用户积分", description = "根据预定义的积分行为调整用户积分 -- 用户管理")
    public Result<String> adjustUserPointsByAction(@Parameter(description = "用户ID") @PathVariable Long id, @Parameter(description = "积分行为代码") @PathVariable int actionCode) {
        PointActionEnum action = PointActionEnum.fromCode(actionCode);
        userService.adjustUserPointsByAction(id, action);
        return Result.success("积分调整成功");
    }

    @GetMapping("/current")
    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的信息 -- 个人信息")
    public Result<User> getCurrentUser() {
        User user = userService.getCurrentUser();
        return Result.success(user);
    }

    @PutMapping("/current")
    @Operation(summary = "更新当前用户信息", description = "更新当前登录用户的个性设置信息 -- 个性设置")
    public Result<User> updateCurrentUser(@Valid @RequestBody UpdatePersonalityDTO userDto) {
        userService.updateCurrentUser(userDto);
        return Result.success(null);
    }

    @PutMapping("/profile")
    @Operation(summary = "更新用户更多信息", description = "更新当前用户的更多信息，如手机号、邮箱等 -- 更多信息")
    public Result<Void> updateProfile(@Valid @RequestBody UpdateProfileDTO dto) {
        userService.updateProfile(dto);
        return Result.success();
    }

    @PostMapping ("/change-password")
    @Operation(summary = "修改密码", description = "用户修改登录密码 -- 更多信息")
    public Result<Void> changePassword(@RequestBody ChangePasswordDTO dto) {
        userService.changePassword(dto);
        return Result.success();
    }

    /**
     * 根据角色编码获取角色代码
     *
     * @param roleCode 角色编码
     * @return 角色代码
     */
    private String getRoleCode(Integer roleCode) {
        if (roleCode == null) {
            return "USER";
        }
        return switch (roleCode) {
            case 0 -> "USER";      // 普通用户
            case 1 -> "ADMIN";     // 管理员
            case 2 -> "SUPER_ADMIN"; // 超级管理员
            default -> "USER";
        };
    }

    private User convertToUser(CreateUserDTO dto) {
        User user = new User();
        user.setUsername(dto.getUsername());
        user.setNickname(dto.getNickname());
        user.setPassword(dto.getPassword());
        user.setPhone(dto.getPhone());
        user.setEmail(dto.getEmail());
        user.setCollegeId(dto.getCollegeId());
        user.setGender(dto.getGender());
        user.setBirthday(dto.getBirthday());
        user.setMajorClass(dto.getMajorClass());
        user.setStudentNo(dto.getStudentNo());
        user.setRoleCode(getRoleCode(dto.getRoleCode()));
        user.setAuthType(dto.getAuthType());
        user.setStatus(dto.getStatus() != null ? dto.getStatus() : 0);
        return user;
    }

    private User convertToUser(UpdateUserDTO dto) {
        User user = new User();
        user.setId(dto.getId());
        user.setUsername(dto.getUsername());
        user.setNickname(dto.getNickname());
        user.setPhone(dto.getPhone());
        user.setEmail(dto.getEmail());
        user.setCollegeId(dto.getCollegeId());
        user.setGender(dto.getGender());
        user.setBirthday(dto.getBirthday());
        user.setMajorClass(dto.getMajorClass());
        user.setStudentNo(dto.getStudentNo());
        user.setRoleCode(getRoleCode(dto.getRoleCode()));
        user.setAuthType(dto.getAuthType());
        user.setStatus(dto.getStatus());
        user.setAvatar(dto.getAvatar());
        user.setSignature(dto.getSignature());
        user.setTagsJson(dto.getTagsJson());
        user.setUserNo(dto.getUserNo());
        user.setRegisterTime(dto.getRegisterTime());
        user.setLastLoginTime(dto.getLastLoginTime());
        user.setLastNicknameUpdateTime(dto.getLastNicknameUpdateTime());
        user.setUpdateTime(dto.getUpdateTime());
        user.setLoginFailCount(dto.getLoginFailCount());
        user.setLockTime(dto.getLockTime());
        user.setPasswordUpdateTime(dto.getPasswordUpdateTime());
        return user;
    }
}